<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>

    <SlotUsage>
      <template #default="obj">
        <div>
          传递的插槽内容 -- {{ obj.username }}
        </div>
      </template>
    </SlotUsage>

    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
            @click="showDrawer('add')">
            添加面经
          </el-button>
        </div>
      </template>
      <el-table
        :data="list"
        style="width: 100%">
        <el-table-column
          prop="stem"
          label="标题"
          width="200">
        </el-table-column>
        <el-table-column
          prop="creator"
          label="作者">
        </el-table-column>
        <el-table-column
          prop="likeCount"
          label="点赞">
        </el-table-column>
        <el-table-column
          prop="views"
          label="浏览数">
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="更新时间"
          width="200">
        </el-table-column>
        <el-table-column label="操作">
          <!-- 如果该列要渲染自定义内容，需要使用插槽 -->
          <!-- <el-button type="primary" size="small">编辑</el-button> -->
          <!-- 表格某一列可以使用作用域插槽接收组件内部传递出来的数据 -->
          <!-- row：行的数据 -->
          <!-- column：列的信息 -->
          <!-- $index：索引 -->
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-view" @click="showDrawer('preview', row.id)"></i>
              <i class="el-icon-edit-outline" @click="showDrawer('edit', row.id)"></i>
              <i class="el-icon-delete" @click="deleteArtile(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- current-page：当前是第几页 -->
      <!-- page-size：每页显示多少条数据 -->
      <!-- total：总条数 -->
      <!-- layout：用于给分页器布局 -->
      <!-- 分页内部的计算： 总共有多少页 = Math.ceil(总条数 / 每页显示多少条) -->
      <!-- Math.ceil(100 / 30) => 4 -->

      <!-- current-change：每次分页第几页的页数发生变化，都会触发该事件 -->
      <el-pagination
        @current-change="handleCurrentChange"
        background
        :current-page="current"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- visible：控制抽屉显示与隐藏的 -->
    <!-- direction：控制抽屉的打开方向 -->
    <el-drawer
      size="50%"
      :title="title"
      :visible.sync="isShowDrawer"
      direction="rtl"
      @close="drawerClose">
      <div v-if="type === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
      <el-form v-else :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="form.content" @blur="handleBlur"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="isShowDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getArticleList, addArticle, removeArticle, getArticleDetail, editArticle } from '@/api/article'
import SlotUsage from '@/components/slotUsage.vue'

// 引入富文本编辑器的样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 引入富文本编辑器组件
import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'article-page',
  components: {
    quillEditor,
    SlotUsage
  },
  computed: {
    title () {
      // if (this.type === 'add') {
      //   return '添加面经'
      // } else if (this.type === 'edit') {
      //   return '修改面经'
      // } else {
      //   return '面经预览'
      // }
      return this.type === 'add' ? '添加面经' : this.type === 'edit' ? '修改面经' : '面经预览'
    }
  },
  data () {
    return {
      list: [],
      current: 1,
      pageSize: 10,
      total: 0,
      // 控制抽屉的显示与隐藏的值
      isShowDrawer: false,
      // 表单数据对象
      form: {
        stem: '',
        content: ''
      },
      // 表单验证规则对象
      rules: {
        stem: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      type: ''
    }
  },
  async created () {
    this.getArticleList()
  },
  methods: {
    async handleCurrentChange (page) {
      // page：最新的当前页
      console.log(page)
      // 1. 修改当前页数
      this.current = page
      // 2. 重新发起请求
      this.getArticleList()
    },
    // 获取文章列表数据
    async getArticleList () {
      const res = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 显示抽屉
    async showDrawer (type, id) {
      this.isShowDrawer = true
      this.type = type
      // 不是添加的话，要做数据回显
      if (type !== 'add') {
        const res = await getArticleDetail(id)
        // console.log(res)
        this.form = res.data
      }
    },
    // 富文本编辑器失焦
    handleBlur () {
      // console.log('失焦了')
      // 对某个表单项，单独做校验（主动校验）
      // validateField('要验证的表单项的值')
      this.$refs.formRef.validateField('content')
    },
    // 抽屉关闭后触发的事件
    drawerClose () {
      if (this.type !== 'preview') {
        // 清空表单内容和校验结果
        this.$refs.formRef.resetFields()
      }
      // 手动清空表单数据
      this.form = {
        stem: '',
        content: ''
      }
    },
    // 添加面经
    submit () {
      // 兜底校验
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return
        // 发起请求
        if (this.type === 'add') {
          // 添加面经接口
          await addArticle(this.form)
        } else {
          // 修改面经接口
          await editArticle({
            id: this.form.id,
            stem: this.form.stem,
            content: this.form.content
          })
        }
        const msg = this.type === 'add' ? '添加成功' : '修改成功'
        // 提示用户
        this.$message.success(msg)
        // 关闭抽屉
        this.isShowDrawer = false
        // 刷新列表
        this.current = 1 // 每次从第一页开始查列表数据
        this.getArticleList()
      })
    },
    // 删除文章
    async deleteArtile (id) {
      // 发起请求
      await removeArticle(id)
      // 提示用户
      this.$message.success('删除成功')
      // 从第一页开始请求
      this.current = 1
      // 刷新列表
      this.getArticleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
